//封装的消息提示函数
import {
	showMsg
} from '@/utils/interact/index.js'
// 全局请求封装
const base_url = 'https://www.yuexintec.fun/yx'
// 请求超出时间
const timeout = 5000

// 节流处理
export function saveTraffic(options) {
	let saveApiList = [];

	// 闭包
	return function(params) {
		if (saveApiList.indexOf(options.url) !== -1) return;

		// 当前url不在数组中，可以发起请求，添加到数组中
		saveApiList.push(options.url)
		uni.showLoading({
			title: '加载中',
		})
		return new Promise((resolve, reject) => {
			uni.request({
				url: base_url + options.url,
				method: options.method || 'GET',
				data: params || {},
				header: options.header || {
					'content-type': 'application/json'
				},
				timeout: timeout,
				success: (res) => {
					if (res.statusCode === 200) {
						resolve(res.data)
					} else {
						console.error(res.statusCode);
						showMsg('获取数据失败', 'error')
					}
				},
				fail: (err) => {
					showMsg('出错啦', 'error')
					reject(err)
				},
				complete: () => {
					// 请求完成，从数组中移除
					saveApiList = saveApiList.filter(u => u !== options.url);
					uni.hideLoading()

				}
			})
		})
	}
}
// 封装请求
export function request(options) {
	uni.showLoading({
		title: '加载中',
	})
	return new Promise((resolve, reject) => {
		uni.request({
			url: base_url + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: options.header || {
				'content-type': 'application/json'
			},
			timeout: timeout,
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				showMsg('请求错误', 'error')
				reject(err)
			},

			complete: () => {
				uni.hideLoading()
			}
		})
	})
}